package cn.rdtimes.wolfdsp.core.job;

import cn.rdtimes.wolfdsp.core.data.ScheduledInstance;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * 调度一个流程生成调度实例
 *
 * @author BZ
 */
class PerformScheduledInstance {
    private final ScheduledInstance scheduledInstance;
    private final CronExpression cronExpression;
    private final String jobId;

    private volatile ScheduledFuture<?> future;

    PerformScheduledInstance(ScheduledInstance scheduledInstance) {
        this.scheduledInstance = scheduledInstance;
        this.jobId = scheduledInstance.getJobId();

        try {
            this.cronExpression = new CronExpression(scheduledInstance.getCronExp());
        } catch (Exception e) {
            throw new IllegalStateException("cronException is error");
        }
    }

    public ScheduledInstance getScheduledInstance() {
        return scheduledInstance;
    }

    public String getJobId() {
        return jobId;
    }

    public ScheduledFuture<?> getFuture() {
        return future;
    }

    public void setFuture(ScheduledFuture<?> future) {
        this.future = future;
    }

    // 计算下一次触发的时间,空值说明不需要再次调度
    final Date calcNextTime(Date d) {
        Date now = new Date(d.getTime());
        return cronExpression.getNextValidTimeAfter(now);
    }

}
